﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace HF.Software.ClassLib
{
    /// <summary>
    /// hef创建于2014.11.04
    /// 用于系统日志记录
    /// </summary>
    public class ClsLog
    {
        #region var

        private string sLogFile = "";
        private StreamWriter oStreasmWriter = null;
        private FileStream oFileStream = null;

        #endregion

        #region create

        public ClsLog() { }

        public ClsLog(string _sFileName)
            : this()
        {
            this.sLogFile = _sFileName;
            this.fnCreateDirectory(sLogFile);
        }

        #endregion

        #region fun

        /// <summary>
        /// 写日志文件
        /// </summary>
        /// <param name="_sInfo">内容</param>
        public void fnLog(string _sInfo)
        {
            try
            {
                System.IO.FileInfo oFileInfo = new System.IO.FileInfo(sLogFile);
                if (!oFileInfo.Exists)
                {
                    oFileStream = oFileInfo.Create();
                    oStreasmWriter = new StreamWriter(oFileStream);
                }
                else
                {
                    oFileStream = oFileInfo.Open(FileMode.Append, FileAccess.Write);
                    oStreasmWriter = new StreamWriter(oFileStream);
                }
                //byte[] bArrUTF = Encoding.UTF8.GetBytes(_sInfo);
                //_sInfo = Encoding.GetEncoding("GB2312").GetString(bArrUTF);
                oStreasmWriter.WriteLine(DateTime.Now + ": " + _sInfo);
                oStreasmWriter.WriteLine("======================================================");
            }
            finally
            {
                if (oStreasmWriter != null)
                {
                    oStreasmWriter.Close();
                    oStreasmWriter.Dispose();
                    oFileStream.Close();
                    oFileStream.Dispose();
                }
            }
        }

        /// <summary>
        /// 创建文件
        /// </summary>
        /// <param name="_sInfoPath">文件完整路径</param>
        public void fnCreateDirectory(string _sInfoPath)
        {
            DirectoryInfo oDirectoryInfo = Directory.GetParent(_sInfoPath);
            if (!oDirectoryInfo.Exists)
            {
                oDirectoryInfo.Create();
            }
        }

        #endregion

    }
}
